#include <iostream>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <assert.h>
using namespace std;

/*
先创建管道， 进而创建子进程， 父子进程使用管道进行通信
父进程向管道当中写“i am father”， 
子进程从管道当中读出内容, 并且打印到标准输出
*/
int main()
{
    //创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n != -1);
    (void)n;

    //创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        //子进程 关闭写
        close(pipefd[1]);
        char buffer[100];
        ssize_t s = read(pipefd[0],buffer,sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << buffer << endl;
        }
    }
    //父进程 关闭读
    close(pipefd[0]);
    string message = "i am father";
    char buffer[100];
    snprintf(buffer,sizeof(buffer),"%s",message.c_str());
    write(pipefd[1],buffer,sizeof(buffer));

    pid_t ret = waitpid(id,nullptr,0);
    assert(ret);
    (void)ret;
    close(pipefd[1]);
    return 0;
}
